<script setup>

import {getCurrentInstance, onMounted, ref} from "vue";
import { nextTick } from 'vue';
import {useUserStore} from "@/store/User.js";
import {color} from "echarts";
import {ChromeFilled, SwitchFilled} from "@element-plus/icons-vue";
const { proxy } = getCurrentInstance();

let promises = null;
const userStore = useUserStore();
const travelList = ref();
const schedulesList = ref();
const approvalMap = ref(new Map());
const travelMap = ref(new Map());
const nowTravelId = ref(0);
const travelApprovalDate = ref();
const advanceApprovalDate = ref();
const nowReimbursementId = ref(0);
const reimbursementData = ref({});
const reimbursementApprovalDate = ref();

const approval = ref({
  travelApproval: 0,
  advanceApproval: 0,
  reimbursementApprovalMa: 0,
  reimbursementApprovalFi: 0,
});

const travel = ref({
});

onMounted(async () => {
  console.log(userStore.getUser().userId);

  // 获取出差列表
  let result = await proxy.Request({
    url: proxy.Api.getAllTravelListByUserId,
    params: {
      userId: userStore.getUser().userId,
    },
  });
  travelList.value = result.data;
  console.log(travelList);

  // 获取出差审批信息并填充 approvalMap 和 travelMap
  promises = await travelList.value.map(async (item) => {
    console.log(item.travelId);
    let result = await proxy.Request({
      url: proxy.Api.getApprovalByTravelId,
      showLoading: true,
      params: {
        travelId: item.travelId
      },
    });

    console.log(result.data);
    // 填充 approvalMap 和 travelMap
    approvalMap.value.set(item.travelId.toString(), result.data);
    travelMap.value.set(item.travelId.toString(), item);
  });
  // 等待所有异步请求完成
  await Promise.all(promises)
});

const getTravelStatus = (travelId) => {
  let approvalData = approvalMap.value.get(travelId.toString());
  let travelData = travelMap.value.get(travelId.toString());
  if (!approvalData) {
    console.log(`approvalMap does not contain data for travelId: ${travelId}`);
    return null;
  }
  return judgeStatus(approvalData.travelApproval, approvalData.reimbursementApprovalMa, approvalData.reimbursementApprovalFi, travelData.endDate);
};

const handleSelect = async (travelId) =>{
  console.log(travelId);
  nowTravelId.value = travelId
  travel.value = travelMap.value.get(travelId.toString());
  approval.value = approvalMap.value.get(travelId.toString());

  let result = await proxy.Request({
    url: proxy.Api.getAllScheduleListByTravelId,
    showLoading: true,
    params: {
      travelId: travelId,
    },
  });
  schedulesList.value = result.data;

  if(approval.value.travelApproval !== 0){
    let travelApproval = await proxy.Request({
      url: proxy.Api.getTravelApprovalByTravelId,
      showLoading: true,
      params: {
        travelId: travelId,
      },
    });
    travelApprovalDate.value = await travelApproval.data?.date
  }

  if(approval.value.advanceApproval !== 3 && approval.value.advanceApproval !== 0 ) {
    let advanceApproval = await proxy.Request({
      url: proxy.Api.getAdvanceApprovalByAdvanceId,
      showLoading: true,
      params: {
        advanceId: travelId,
      },
    });
    advanceApprovalDate.value = await advanceApproval.data?.date
  }

  let reimbursement = await proxy.Request({
    url: proxy.Api.getReimbursementByTravelId,
    showLoading: true,
    params: {
      travelId: travelId,
    },
  });
  if(reimbursement.data){
    reimbursementData.value = await reimbursement.data
    nowReimbursementId.value = reimbursementData.value.reimbursementId
    console.log(nowReimbursementId.value)
  }
  else{
    nowReimbursementId.value = 0;
    console.log(nowReimbursementId.value)
  }

  if(approval.value.reimbursementApprovalFi !== 0 && approval.value.reimbursementApprovalMa !== 0) {
    let reimbursementApprovalFi = await proxy.Request({
      url: proxy.Api.getReimbursementApprovalFiByReimbursementId,
      showLoading: true,
      params: {
        reimbursementId: nowReimbursementId.value,
      },
    });
    let reimbursementApprovalMa = await proxy.Request({
      url: proxy.Api.getReimbursementApprovalMaByReimbursementId,
      showLoading: true,
      params: {
        reimbursementId: nowReimbursementId.value,
      },
    });
    if(reimbursementApprovalFi&&reimbursementApprovalMa){
      reimbursementApprovalDate.value =
          new Date(reimbursementApprovalFi.data?.date).getTime() > new Date(reimbursementApprovalMa.data?.date).getTime() ?
              reimbursementApprovalFi.data?.date : reimbursementApprovalMa.data?.date;
    }
  }
  console.log(travel.value);
  console.log(approval);
}
const judgeStatus = (travelApproval, reimbursementApprovalMa, reimbursementApprovalFi, date) =>{
  let status = new Date(date).getTime() > new Date().getTime()
  if(travelApproval === 1 && reimbursementApprovalMa === 1 && reimbursementApprovalFi === 1){
    return {
      type: "success",
      travelStatus: "已完成"
    }
  }
  if(travelApproval === 0){
    return {
      type: "info",
      travelStatus: "待审批"
    }
  }
  if(travelApproval === 2){
    return {
      type: "danger",
      travelStatus: "未通过"
    }
  }
  if(travelApproval === 1 && status){
    return {
      type: "primary",
      travelStatus: "出差中"
    }
  }

  if(travelApproval === 1 && !(reimbursementApprovalMa === 1 || reimbursementApprovalFi === 1)){
    return {
      type: "danger",
      travelStatus: "报销未通过"
      }
  }
    if(travelApproval === 1 && !status){
    return {
      type: "warning",
      travelStatus: "待报销"
    }
  }


}

</script>

<template>
  <el-row class="tac">
    <el-col :span="4">
    <div class='selectTravel' >
      <div style="font-size: 24px; font-weight: bold; color: #557096; width: 100%; text-align: center; margin: 10px 0 0">出差记录</div>
      <div style="font-size: 24px; font-weight: bold; background-color: #4b4b4b; width: 100%; text-align: center; margin: 10px 0 ; height: 2px"></div>
      <el-menu
          active-text-color=""
          background-color=""
          class="el-menu-vertical-demo"
          default-active="2"
          text-color=""
          id="travelMenu"
          @select="handleSelect"
      >
        <el-menu-item v-for="travel in travelList" :index="travel.travelId" >
          <el-icon><ChromeFilled /></el-icon>
          <span> {{ travel.applyDate }} </span>
          <el-divider direction="vertical"/>
          <el-tag :key="travel.travelId" :type="getTravelStatus(travel.travelId)?.type">{{ getTravelStatus(travel.travelId)?.travelStatus }}</el-tag>
        </el-menu-item>
      </el-menu>
    </div>
    </el-col>

    <!--出差流程部分 -->

    <el-col  :span="20">
      <div class="travelInfo">
        <el-timeline v-if="nowTravelId !== 0">
          <!--出差申请信息 -->
        <el-timeline-item :timestamp="travel?.applyDate" placement="top" size="large" style="max-width: 1300px">
          <el-card>
            <el-descriptions
                title="出差申请信息"
                direction="vertical"
                :column="4"
                size="default"
                border
                style="max-width: 100vh"
            >
              <el-descriptions-item label="出差原因" :span="2" :key="nowTravelId">{{ travel?.travelReason }}</el-descriptions-item>
              <el-descriptions-item label="开始时间" :span="1" :key="nowTravelId">
                <el-tag type="primary" size="large">{{ travel?.startDate }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="结束时间" :span="1">
                <el-tag type="warning" size="large">{{ travel?.endDate }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="出差详情">{{ travel?.travelDetail }}</el-descriptions-item>
            </el-descriptions>
            <el-divider style="font-size: 100px; "></el-divider>
            <div style="font-size: 16px;font-weight: bold">出差行程规划</div>
            <el-carousel type="card" height="310px">
              <el-carousel-item v-for="schedule in schedulesList" :key="schedule" style="border-radius: 20px">
                <el-button style="margin: 10px" size="small" circle />
                <el-descriptions
                    title=""
                    direction="vertical"
                    :column="4"
                    size="default"
                    border
                    style="margin: 5px 10px 5px 10px;"
                >
                  <el-descriptions-item label="行程任务" :span="4">{{schedule.task}}</el-descriptions-item>
                  <el-descriptions-item label="行程地点" :span="2">{{schedule.location}}</el-descriptions-item>
                  <el-descriptions-item label="开始时间" :span="1">
                    <el-tag type="primary" size="large">{{schedule.startDate}}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="结束时间" :span="1">
                    <el-tag type="warning" size="large">{{schedule.endTime}}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="行程详情">{{schedule.scheduleDetail}}</el-descriptions-item>
                </el-descriptions>
              </el-carousel-item>
            </el-carousel>
            <el-divider style="font-size: 100px; "></el-divider>
            <el-descriptions
                title="预算申请信息"
                direction="vertical"
                :column="4"
                size="default"
                style="max-width: 100vh"
                border
            >
              <el-descriptions-item label="餐饮费" :span="1"><el-tag type="warning" size="large">￥{{ travel?.foodCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="交通费" :span="1"><el-tag type="primary" size="large">￥{{ travel?.transportCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="住宿费" :span="1"><el-tag type="success" size="large">￥{{ travel?.hotelCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="预支款" :span="1"><el-tag type="danger" size="large">￥{{ travel?.advancePayment }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="预算明细">{{ travel?.costDetail }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-timeline-item>

          <!--出差申请结果 -->
          <el-timeline-item v-if="approval.travelApproval !== 0" :timestamp="travelApprovalDate" placement="top" size="large" style="max-width: 800px" >
            <el-card>
              <el-result v-if="approval.travelApproval === 1" icon="success" title="出差申请通过" subTitle="公司旅人祝你旅途愉快"/>
              <el-result v-if="approval.travelApproval === 2" icon="error" title="出差申请被驳回" subTitle="请重新申请出差"/>
              <el-descriptions
                  title=""
                  :rowspan="2"
                  size="default"
                  style="max-width: 800px"
                  border
              >
                <el-descriptions-item v-if="approval.travelApproval === 2" label="原因" :span="3" label-class-name="label" class-name="content-success" label-align="center">
                  {{ approval?.travelRejection }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-timeline-item>

          <!--预支款申请结果 -->
          <el-timeline-item v-if="approval.advanceApproval !== 3 && approval.advanceApproval !== 0 " :timestamp="advanceApprovalDate" size="large" placement="top" style="max-width: 800px" >
            <el-card>
              <el-result v-if="approval.advanceApproval === 1" icon="success" title="预支款申请通过" subTitle="公司旅人祝你旅途愉快"/>
              <el-result v-if="approval.advanceApproval === 2" icon="error" title="预支款申请未通过" subTitle="你的预支款未被批准"/>
              <el-descriptions
                  title=""
                  :rowspan="2"
                  size="default"
                  style="max-width: 800px"
                  border
              >
                <el-descriptions-item v-if="approval.advanceApproval === 2" label="原因" :span="3" label-class-name="label" class-name="content" label-align="center">
                  {{ approval?.advanceRejection }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-timeline-item>

          <!--开始出差 -->
          <el-timeline-item v-if="approval.travelApproval === 1 " :timestamp="travel?.startDate" placement="top" size="large" style="max-width: 300px" >
            <el-card>
              <el-alert title="开 始 出 差" type="success" :closable="false" center/>
            </el-card>
          </el-timeline-item>

          <!--出差结束 -->
          <el-timeline-item v-if="approval.travelApproval === 1 && new Date(travel?.endDate) <= new Date()" :timestamp="travel?.endDate" placement="top" size="large" style="max-width: 300px" >
            <el-card>
              <el-alert title="出 差 结 束" type="warning" :closable="false" center/>
            </el-card>
          </el-timeline-item>

          <!--报销申请信息 -->
        <el-timeline-item v-if='nowReimbursementId !== 0' :timestamp="reimbursementData.applyDate" placement="top" size="large" style="max-width: 100vh" >
          <el-card>
            <el-descriptions
                title="报销申请信息"
                direction="vertical"
                :column="4"
                size="default"
                border
            >
              <el-descriptions-item label="餐饮费" :span="1"><el-tag type="warning" size="large">￥{{ reimbursementData?.foodCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="交通费" :span="1"><el-tag type="primary" size="large">￥{{ reimbursementData?.transportCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="住宿费" :span="2"><el-tag type="success" size="large">￥{{ reimbursementData?.hotelCost }}</el-tag></el-descriptions-item>
              <el-descriptions-item label="预算明细" :span="3">{{ reimbursementData?.detail }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-timeline-item>

          <!--报销申请结果 -->
          <el-timeline-item v-if="approval.reimbursementApprovalMa === 2 ||(approval.reimbursementApprovalMa !== 0 && approval.reimbursementApprovalFi !== 0) " :timestamp="reimbursementApprovalDate" size="large" placement="top" style="max-width: 800px" >
            <el-card>
              <el-result v-if="approval.reimbursementApprovalMa === 1 && approval.reimbursementApprovalFi === 1" icon="success" title="报销申请通过" subTitle="公司旅人祝你旅途愉快"/>
              <el-result v-if="approval.reimbursementApprovalMa === 2 || approval.reimbursementApprovalFi === 2" icon="error" title="报销申请未通过" subTitle="你的报销申请未被批准"/>
              <el-descriptions
                  title=""
                  :rowspan="2"
                  size="default"
                  style="max-width: 800px"
                  border
              >

                <el-descriptions-item v-if="approval.reimbursementApprovalMa === 2 || approval.reimbursementApprovalFi === 2" label="原因" :span="3" label-class-name="label" class-name="content" label-align="center">
                  经理：{{ approval?.reimbursementRejectionMa }}
                  <el-divider/>
                  财务人员：{{ approval?.reimbursementRejectionFi }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-timeline-item>

          <!--出差结束 -->
          <el-timeline-item v-if="approval.reimbursementApprovalMa === 1 && approval.reimbursementApprovalFi === 1" :timestamp="reimbursementApprovalDate" placement="top" style="max-width: 300px"
                            size="large">
            <el-card>
              <el-alert title="出 差 流 程 结 束" type="info" :closable="false" center/>
            </el-card>
          </el-timeline-item>
      </el-timeline>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.selectTravel{
  background-color: #bbcce0;
  border-radius: 20px;
  height: 85vh;
  padding: 5px;
  margin: 0 10px;
}

.travelInfo{
  background-color: #f7fcfd;
  border-radius: 20px;
  padding: 30px 10px;
  box-shadow: 0 0 15px 0 rgba(122, 122, 122, 0.3);
  -webkit-box-shadow: 0 0 15px 0 rgba(122, 122, 122, 0.3);
  -moz-box-shadow: 0 0 15px 0 rgba(122, 122, 122, 0.3);
  max-height: 85vh; /* 固定内容区域的最大高度 */
  min-height: 85vh;
  overflow-y: auto; /* 启用垂直滚动条 */
}
:deep(.label){
  background: var(--el-color-danger-light-7) !important;
}
:deep(.label-success){
  background: var(--el-color-success-light-7) !important;
}
.el-carousel__item:nth-child(n) {
  background-color: #c5c5c5;
}
.card{

}
</style>